package com.xuedakun.xasdk.net.okhttp.upload;

import android.support.annotation.NonNull;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;

/**
 * Created by xuedakun on 2017/6/8 11:39
 * 上传文件使用的requestBody
 *
 * @version : v1.0
 * @project : xasdk
 * @Email : dakun611@Gmail.com
 */

public final class UploadRequestBody extends RequestBody {

    private BufferedSink bufferedSink;

    private final IUploadListener listener;

    private final RequestBody requestBdy;

    public UploadRequestBody(@NonNull IUploadListener listener, @NonNull RequestBody requestBody) {
        this.listener = listener;
        this.requestBdy = requestBody;
    }

    @Override
    public MediaType contentType() {
        return requestBdy.contentType();
    }

    @Override
    public long contentLength() throws IOException {
        return requestBdy.contentLength();
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        if (bufferedSink == null) {
            bufferedSink = Okio.buffer(sink(sink));
        }
        requestBdy.writeTo(bufferedSink);
        //必须调用flush，否则最后一部分数据可能不会被写入
        bufferedSink.flush();
    }

    private Sink sink(Sink sink) {
        return new ForwardingSink(sink) {
            private long current;
            private long total;

            @Override
            public void write(Buffer source, long byteCount) throws IOException {
                super.write(source, byteCount);
                if(current == 0) {
                    if (listener != null) {
                        listener.onUploadStatusChange(UploadManager.STATUS_LOAD);
                    }
                }
                if (total == 0) {
                    total = contentLength();
                }
                current += byteCount;
                if (listener != null) {
                    listener.onUploadProgress(current, total);
                }
            }
        };
    }
}
